﻿using System;
using System.Web.Security;
using System.Windows.Forms;
using HRM.Properties;

namespace HRM
{
    public partial class frmConfig : FormBase
    {
        //frmSplash Splasher;
        DialogResult _retVal;
        public frmConfig()
        {
            InitializeComponent();
            KeyPreview = true;
            _retVal = DialogResult.Cancel;
            LoadLanguge();
            txtUser.Text = Settings.Default.LastUser;
            txtAddress.Text = Settings.Default.ServiceAddress;
            if (txtUser.Text.Trim().Length == 0)
                txtUser.Focus();
            else
                txtPassword.Focus();
        }

        protected override void Init_Control()
        {
            FormGlobals.Control_SetRequired(txtAddress, txtPassword, txtUser);
        }

        public override void Show_Form()
        {
            Show();
        }

        private bool CheckLogin()
        {
            try
            {
                if (!FormGlobals.Panel_CheckError(pnlInput))
                    return false;
                //
                FormGlobals.App_ProgressShow(delegate()
                {
                    //Gán địa chỉ mới
                    Settings.Default.ServiceAddress = txtAddress.Text;

                    //Lưu vào App.Config, sử dụng DAL
                    var sLoginConnect = txtAddress.Text.Substring(0, txtAddress.Text.LastIndexOf('/'));
                    Globals.Application_SetConfig("RemoteConnect", sLoginConnect);
                    Globals.Application_SetConfig("LoginConnect", "net." + sLoginConnect);
                    Globals.Application_SetConfig("WorkingConnect", "net." + sLoginConnect);
                    //
                    //lưu proxy
                    Settings.Default.UseProxy = chkProxy.Checked;
                    Settings.Default.ProxyAddress = txtProxyAddress.Text;
                    Settings.Default.ProxyPort = Convert.ToInt32(numPort.Value);

                    ProxyConfig.ReNewAddress();

                    Program.strUserName = txtUser.Text.ToUpper().Trim();
                    Program.strPassword = FormsAuthentication.HashPasswordForStoringInConfigFile(txtPassword.Text.Trim(), "SHA1");

                    var wcfUser = Service.User();
                    var userInf = wcfUser.User_GetUserInfo(txtUser.Text);

                    var logged = true;
                    if (userInf == null)
                    {
                        MessageBox.Show(HrmResources.USERNAME_OR_PASS_INVALID, HrmResources.NOTIFY, MessageBoxButtons.OK);
                        logged = false;
                    }
                    if (logged && txtPassword.Text != userInf.PassWord)
                    {
                        MessageBox.Show(HrmResources.USERNAME_OR_PASS_INVALID, HrmResources.NOTIFY, MessageBoxButtons.OK);
                        logged = false;
                    }

                    //Lưu lại cấu hình
                    if (logged)
                    {
                        Settings.Default.LastUser = txtUser.Text;
                        Settings.Default.Save();
                        UIParamater.FullNameOfUser = userInf.FullName;
                        Program.intBranchID = userInf.BranchID == "" ? 0 : Convert.ToInt32(userInf.BranchID);
                        Service.LoadSystem();
                        Service.LoadRoleRight();
                        var wcfEmployee = Service.Employee();
                        LocalDB.dtTableEmployee = wcfEmployee.Employee_GetAllWithBranch(Program.intBranchID).Tables[0];
                    }
                }, "Kiểm tra cấu hình");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
            return true;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (CheckLogin())
            {
                _retVal = DialogResult.OK;
                Close();
            }
        }

        void LoadLanguge()
        {
            Text = Tag != null ? UpdateUI.GetString(this.Tag.ToString()) : Text;
            UpdateUI.Load_Panel(ref pnlInput);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void frmConfig_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Enter:
                    if (!e.Alt && !e.Control)
                    {
                        this.ProcessTabKey(!e.Shift);
                        e.Handled = true;
                    }
                    break;
                case Keys.Escape:
                    Dispose();
                    Close();
                    break;
            }
        }

        private void frmConfig_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult = _retVal;
        }

        //Kiểm tra proxy
        private void chkProxy_CheckedChanged(object sender, EventArgs e)
        {
            txtProxyAddress.Enabled = chkProxy.Checked;
            numPort.Enabled = chkProxy.Checked;

            if (chkProxy.Checked && Utilities.GetProxy.GetProxyStatus() == 1)
            {
                var proxy = Utilities.GetProxy.GetProxyName();
                string[] temp;
                if (proxy.Contains("http"))
                {
                    temp = proxy.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (string item in temp)
                    {
                        if (item.Contains("https="))
                        {
                            var temp1 = item.Substring(6);
                            var temp2 = temp1.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                            txtProxyAddress.Text = temp2[0];
                            numPort.Value = Convert.ToInt32(temp2[1]);
                        }
                    }
                }
                else
                {
                    temp = proxy.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                    txtProxyAddress.Text = temp[0];
                    numPort.Value = Convert.ToInt32(temp[1]);
                }
            }
        }

        private void frmConfig_Load(object sender, EventArgs e)
        {

        }
    }
}
